package cn.fl.warrant.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.dto.SysUsrDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.warrant.service.IArcTransferMainService;
import cn.fl.warrant.transform.ArcBorrowMainVOTransform;
import cn.fl.warrant.transform.ArcSysFlowSHVOTransform;
import cn.fl.warrant.transform.ArcTransferMainVOTransform;
import cn.fl.warrant.vo.ArcBorrowMainVO;
import cn.fl.warrant.vo.ArcSysFlowSHVO;
import cn.fl.warrant.vo.ArcTransferMainVO;
import fl.flow.facade.flow.api.IFlowApiService;
import fl.flow.facade.flow.condition.SysFlowSHQueryCondition;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.flow.facade.flow.dto.SysFlowSHDTO;
import fl.warrant.facade.archive.api.IArcTransferMainApiService;
import fl.warrant.facade.archive.condition.ArcTransferMainQueryCondition;
import fl.warrant.facade.archive.constant.ArchiveConstants;
import fl.warrant.facade.archive.dto.ArcTransferMainDTO;

/**
 * @Description: 结清移交 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class ArcTransferMainServiceImpl implements IArcTransferMainService {
	
	private static final Logger logger = LoggerFactory.getLogger(IArcTransferMainService.class);
	
	/**
	 * 数据字典
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApi;
	
	@Autowired
	private IArcTransferMainApiService arcTransferMainApiService;
	 @Autowired
	private IFlowApiService flowApiService;
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	  @Autowired
	private ISysUsrApiService sysUsrApiService;
	
	/**
	 * 根据字段代码组获取代码值集合
	 * @param grpCd 代码组值
	 * @param sysCd 系统代码
	 * @param orgCd 组织结构代码
	 * @return 值
	 * @throws BaseException
	 */
	@Override
	public List<KeyValueVO> getKvList(String grpCd) throws BaseException {
		List<KeyValueVO>  keyValueList = null;
		List<SysDictionaryDTO> dictionaryList = this.sysDictionaryApi
				.searchGroup(CurrentThreadContext.getCurrentSysCd(),
						CurrentThreadContext.getCurrentOrgCd(), grpCd);
		if(CollectionUtils.isNotEmpty(dictionaryList)){
			keyValueList = new ArrayList<>();
			for (SysDictionaryDTO sysDictionaryDTO : dictionaryList) {
				KeyValueVO keyValue = new KeyValueVO();
				keyValue.setKey(sysDictionaryDTO.getCode());
				keyValue.setValue(sysDictionaryDTO.getCodeNm());
				keyValueList.add(keyValue);
			}
		}
		return keyValueList;
	}
	
	/**
	 * 根据字段代码组获取代码值集合
	 * @param grpCd 代码组值
	 * @param sysCd 系统代码
	 * @param orgCd 组织结构代码
	 * @return 值
	 * @throws BaseException
	 */
	@Override
	public List<KeyValueVO> getKvDescList(String grpCd) throws BaseException {
		List<KeyValueVO>  keyValueList = null;
		List<SysDictionaryDTO> dictionaryList = this.sysDictionaryApi
				.searchGroup(CurrentThreadContext.getCurrentSysCd(),
						CurrentThreadContext.getCurrentOrgCd(), grpCd);
		if(CollectionUtils.isNotEmpty(dictionaryList)){
			keyValueList = new ArrayList<>();
			for (SysDictionaryDTO sysDictionaryDTO : dictionaryList) {
				KeyValueVO keyValue = new KeyValueVO();
				keyValue.setKey(sysDictionaryDTO.getCodeNm());
				keyValue.setValue(sysDictionaryDTO.getCodeDesc());
				keyValueList.add(keyValue);
			}
		}
		return keyValueList;
	}
	
	@Override
	public ArcTransferMainVO selectById(Long id) throws BaseException{
		return ArcTransferMainVOTransform.toVO(arcTransferMainApiService.selectById(id));
	}

	@Override
	public Long add(ArcTransferMainVO entity) throws BaseException{
		return this.arcTransferMainApiService.add(ArcTransferMainVOTransform.toDTO(entity));
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		return this.arcTransferMainApiService.removeById(id);
	}
	


	@Override
	public boolean update(ArcTransferMainVO entity) throws BaseException{
		return this.arcTransferMainApiService.update(ArcTransferMainVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		return this.arcTransferMainApiService.searchListPage(page);
	}
	@Override
	public Pager selectListForListPage(Pager page) throws BaseException{
		if(null == page)page = new Pager();
		page=this.arcTransferMainApiService.selectListForListPage(page,  CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		
		return page;
	
	}
	/**
	 * 查找申请流程
	 */
	@Override
	public List<ArcSysFlowSHVO> searchFlow(ArcTransferMainQueryCondition condition) throws BaseException{
//		ArcApplyMainQC condition=new ArcApplyMainQC();
//		condition.setContractNo(contractNo);
		if(null == condition){
			BaseLogUtils.error(logger, "searchFlow", "参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		try {
			Pager page=new Pager();
			page.setEveryPage(100);
			page.setCurrentPage(0);
			page.setCondition(condition);
			page=this.arcTransferMainApiService.searchListPage(page);
			List<ArcTransferMainDTO> list = (List<ArcTransferMainDTO>) page.getResultList();
			List<SysFlowSHDTO> searchList=new ArrayList<SysFlowSHDTO>();
			if (list!=null) {
				for (int i = 0; i < list.size(); i++) {
					SysFlowSHQueryCondition qc = new SysFlowSHQueryCondition();
					qc.setSysCd(CurrentThreadContext.getCurrentSysCd());//系统代码
					qc.setWordsInTheTable(ArchiveConstants.ARC_FLOW_S_H_ARC);//表中字
					qc.setDataId(list.get(i).getId());//业务主键
					//qc.setpDefKey(flowCompleteParamsDTO.getProcDefKey());
					qc.setStatus(BaseConstant.IS_YESNO_YES);
					List<SysFlowSHDTO> sList = this.flowApiService.searchFlowSHDTOList(qc);
					searchList.addAll(sList);
				}
			}
			//根据支付表号获取其parentId 多个支付表发起一个流程
			List<ArcTransferMainDTO> tmainList= arcTransferMainApiService.searchListByCondition(condition, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
			if(null!=tmainList && tmainList.size()>0){
				ArcTransferMainDTO tmvo=tmainList.get(0);
				if(null!=tmvo.getParentId()){
						SysFlowSHQueryCondition qcc = new SysFlowSHQueryCondition();
						qcc.setSysCd(CurrentThreadContext.getCurrentSysCd());//系统代码
						qcc.setWordsInTheTable(ArchiveConstants.ARC_FLOW_S_H_ARC);//表中字
						qcc.setDataId(tmvo.getParentId());//业务主键
						//qc.setpDefKey(flowCompleteParamsDTO.getProcDefKey());
						qcc.setStatus(BaseConstant.IS_YESNO_YES);
						List<SysFlowSHDTO> sList = this.flowApiService.searchFlowSHDTOList(qcc);
						searchList.addAll(sList);
				}
			}//end parentId
			
			List<ArcSysFlowSHVO> rList=ArcSysFlowSHVOTransform.toVOList(searchList);
			for (int i = 0; i <rList.size(); i++) {
				ArcSysFlowSHVO vo=rList.get(i);
				List<KeyValueVO>  list1= this.sysDictionaryApiService.getKvList(ArchiveConstants.FLOW_STATUS, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
				if (StringUtils.isBlank(vo.getAudStsCdNm())&&StringUtils.isNotBlank(vo.getAudStsCd())) {
					for (int j = 0; j <list1.size(); j++) {
						if (vo.getAudStsCd().equals(list1.get(j).getKey())) {
							vo.setAudStsCdNm(list1.get(j).getValue());
						}
					}
				}
				if (vo.getCrtUsrId()!=null) {
					SysUsrDTO dto=this.sysUsrApiService.selectSysUsrById(vo.getCrtUsrId(), CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
					if (dto!=null) {
						vo.setCrtUsrIdNm(dto.getUsrNm());
					}
				}
			}
			return rList;
			
		} catch (Exception e) {
			// TODO: handle exception
			BaseLogUtils.error(logger, "searchApplyFlow", "系统错误"+e.getMessage(), CurrentThreadContext.getCurrentUserName());
			return null;
		}
	}
	@Override
	public Long transferApplyStart(ArcTransferMainVO entity) throws BaseException {
		return this.arcTransferMainApiService.transferApplyStart(ArcTransferMainVOTransform.toDTO(entity));
	}
	@Override
	public DataResultDTO addFlowStart(FlowStartParamsDTO flowStartParamsDTO) throws BaseException{
		if(StringUtils.isEmpty(flowStartParamsDTO.getCrtUsrId()) || StringUtils.isEmpty(flowStartParamsDTO.getBusinessKey())){
			BaseLogUtils.info(logger, "addFlowStart", "用户ID和业务数据主键必须要存在!",CurrentThreadContext.getCurrentUserName());
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "用户ID和业务数据主键必须要存在!");
		}
		return this.arcTransferMainApiService.addFlowStart(flowStartParamsDTO);
	}

	@Override
	public Pager selectListForList(Pager page) throws BaseException {
		return this.arcTransferMainApiService.selectListForList(page);
	}
	@Override
	public List selectEarlyLendPayIds()throws BaseException{
		return this.arcTransferMainApiService.selectEarlyLendPayIds();
	}
	@Override
	public List<ArcTransferMainVO> searchListByCondition(ArcTransferMainQueryCondition qc,String sysCd,String orgCd ) throws BaseException{
		return ArcTransferMainVOTransform.toVOList(this.arcTransferMainApiService.searchListByCondition(qc, sysCd,orgCd));
	}

	@Override
	public List<ArcTransferMainVO> searchList(
			ArcTransferMainQueryCondition condition) {
		return ArcTransferMainVOTransform.toVOList(this.arcTransferMainApiService.searchList(condition));
	}



	
}
